#!/usr/bin/env python
# -*- coding:utf8 -*-

"""
@version: 
@author: lh
@license: Apache Licence 
@contact: liuhuan0672@gmail.com
@site: 
@software: PyCharm
@file: 0010.py
@time: 2016/1/20 16:47

第 0010 题：使用 Python 生成字母验证码图片
"""
import os
import random
import string

from PIL import Image, ImageDraw, ImageFont


def generate_authentic_code():
    # Generate random letters
    letters = ''.join([random.choice(string.ascii_letters) for i in range(4)])

    width = 100
    height = 40
    # Generate an image
    im = Image.new("RGB", (width, height), (255, 255, 255))

    # Draw letters on the image
    dr = ImageDraw.Draw(im)
    font = ImageFont.truetype('arial.ttf', 30)
    for i in range(4):
        color = (random.randint(0, 255), random.randint(0, 255), random.randint(0, 255))
        dr.text((5 + i * 20, 5), letters[i], color, font)

    # Change the background color
    for x in range(width):
        for y in range(height):
            if im.getpixel((x, y)) == (255, 255, 255):
                im.putpixel((x, y), (random.randint(0, 255), random.randint(0, 255), random.randint(0, 255)))

    im.save('./result/random_letter.png')


if __name__ == '__main__':
    generate_authentic_code()
